package com.ilink.yanchuangservice.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ilink.ilinkapi.dto.ground.yanchuang.ContentDetail;
import com.ilink.ilinkapi.dto.ground.yanchuang.MemberDTO;
import com.ilink.ilinkapi.dto.ground.yanchuang.ProjectMetadataDTO;
import com.ilink.ilinkapi.dto.ground.yanchuang.TeacherDTO;
import com.ilink.ilinkcommon.service.oss.OssService;
import com.ilink.ilinkcommon.utils.SnowflakeIdGenerator;
import com.ilink.yanchuangservice.entity.PO.YanchuangComment;
import com.ilink.yanchuangservice.entity.PO.YanchuangExhibitionTime;
import com.ilink.yanchuangservice.entity.PO.YanchuangMember;
import com.ilink.yanchuangservice.entity.PO.YanchuangProjectMember;
import com.ilink.yanchuangservice.entity.PO.YanchuangProjectMetadata;
import com.ilink.yanchuangservice.entity.PO.YanchuangProjectTag;
import com.ilink.yanchuangservice.entity.PO.YanchuangProjectTeacher;
import com.ilink.yanchuangservice.entity.PO.YanchuangTag;
import com.ilink.yanchuangservice.entity.PO.YanchuangTeacher;
import com.ilink.yanchuangservice.entity.VO.ProjectDetailResponse;
import com.ilink.yanchuangservice.entity.VO.ProjectSummaryResponse;
import com.ilink.yanchuangservice.mapper.YanchuangCommentMapper;
import com.ilink.yanchuangservice.mapper.YanchuangExhibitionTimeMapper;
import com.ilink.yanchuangservice.mapper.YanchuangMemberMapper;
import com.ilink.yanchuangservice.mapper.YanchuangProjectMemberMapper;
import com.ilink.yanchuangservice.mapper.YanchuangProjectMetadataMapper;
import com.ilink.yanchuangservice.mapper.YanchuangProjectTagMapper;
import com.ilink.yanchuangservice.mapper.YanchuangProjectTeacherMapper;
import com.ilink.yanchuangservice.mapper.YanchuangTagMapper;
import com.ilink.yanchuangservice.mapper.YanchuangTeacherMapper;
import com.ilink.yanchuangservice.service.YanchuangService;
import java.time.LocalDateTime;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;

import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
@CacheConfig(cacheNames = "yanchuang_metadata")
public class YanchuangServiceImpl implements YanchuangService {
    
    private final YanchuangProjectMetadataMapper projectMetadataMapper;
    
    private final YanchuangTagMapper tagMapper;

    private final YanchuangProjectTagMapper projectTagMapper;

    private final YanchuangMemberMapper memberMapper;

    private final YanchuangProjectMemberMapper projectMemberMapper;

    private final YanchuangTeacherMapper teacherMapper;

    private final YanchuangProjectTeacherMapper projectTeacherMapper;

    private final YanchuangCommentMapper commentMapper;

    private final OssService ossService;

    private final YanchuangExhibitionTimeMapper exhibitionTimeMapper;

    private final SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(2, 2);



    @Override
    public void saveProject(ProjectMetadataDTO projectMetadataDTO) {
        Long projectId = idGenerator.nextId();

        // 保存项目基础信息
        YanchuangProjectMetadata project = new YanchuangProjectMetadata();
        project.setCustomPrimary(projectId);
        project.setExhibitionCode(projectMetadataDTO.getExhibitionCode());
        project.setProjectName(projectMetadataDTO.getProjectName());
        project.setProjectImage(projectMetadataDTO.getProjectImage());

        // 将 ContentDetail 中的 words 保存到内容字段，images 序列化后保存到图片字段
        if (projectMetadataDTO.getIntroduction() != null) {
            project.setIntroduction(projectMetadataDTO.getIntroduction().getWords()); // 保存简介文字
            project.setIntroductionImage(
                projectMetadataDTO.getIntroduction().getImages() != null ? JSON.toJSONString(projectMetadataDTO.getIntroduction().getImages()) : null); // 保存简介图片（序列化），处理 null 值
        }

        if (projectMetadataDTO.getInnovation() != null) {
            project.setInnovation(projectMetadataDTO.getInnovation().getWords()); // 保存创新点文字
            project.setInnovationImage(
                projectMetadataDTO.getInnovation().getImages() != null ? JSON.toJSONString(projectMetadataDTO.getInnovation().getImages()) : null); // 保存创新点图片（序列化），处理 null 值
        }

        if (projectMetadataDTO.getValue() != null) {
            project.setValue(projectMetadataDTO.getValue().getWords()); // 保存应用价值文字
            project.setValueImage(
                projectMetadataDTO.getValue().getImages() != null ? JSON.toJSONString(projectMetadataDTO.getValue().getImages()) : null); // 保存应用价值图片（序列化），处理 null 值
        }

        if (projectMetadataDTO.getTeam() != null) {
            project.setTeam(projectMetadataDTO.getTeam().getWords()); // 保存团队介绍文字
            project.setTeamImage(
                projectMetadataDTO.getTeam().getImages() != null ? JSON.toJSONString(projectMetadataDTO.getTeam().getImages()) : null); // 保存团队介绍图片（序列化），处理 null 值
        }

        projectMetadataMapper.insert(project);

        // 保存标签信息（只插入关联表，不修改标签表）
        for (String tagName : projectMetadataDTO.getTags()) {
            // 根据标签名称查询 tag 表，获取对应的标签 ID
            YanchuangTag tagEntity = tagMapper.selectOne(new LambdaQueryWrapper<YanchuangTag>()
                .eq(YanchuangTag::getTagName, tagName));

            if (tagEntity != null) {
                // 获取标签 ID
                Long tagId = tagEntity.getCustomPrimary();

                // 创建项目与标签的关联关系
                YanchuangProjectTag projectTag = new YanchuangProjectTag();
                projectTag.setCustomPrimary(idGenerator.nextId());
                projectTag.setProjectId(projectId);
                projectTag.setTagId(tagId);

                // 插入到项目-标签关联表
                projectTagMapper.insert(projectTag);
            } else {
                log.warn("标签名称 '{}' 在标签表中未找到，无法进行关联操作", tagName);
            }
        }

        // 保存成员信息
        for (MemberDTO member : projectMetadataDTO.getMembers()) {
            YanchuangMember memberEntity = new YanchuangMember();
            Long memberId = idGenerator.nextId();
            memberEntity.setCustomPrimary(memberId);
            memberEntity.setName(member.getMemberName());
            memberEntity.setGrade(member.getGrade());
            memberEntity.setSchool(member.getSchool());
            memberMapper.insert(memberEntity);

            YanchuangProjectMember projectMember = new YanchuangProjectMember();
            projectMember.setCustomPrimary(idGenerator.nextId());
            projectMember.setProjectId(projectId);
            projectMember.setMemberId(memberId);
            projectMemberMapper.insert(projectMember);
        }

        // 保存教师信息
        for (TeacherDTO teacher : projectMetadataDTO.getTeachers()) {
            YanchuangTeacher teacherEntity = new YanchuangTeacher();
            Long teacherId = idGenerator.nextId();
            teacherEntity.setCustomPrimary(teacherId);
            teacherEntity.setName(teacher.getTeacherName());
            teacherEntity.setSchool(teacher.getTeacherSchool());
            teacherMapper.insert(teacherEntity);

            YanchuangProjectTeacher projectTeacher = new YanchuangProjectTeacher();
            projectTeacher.setCustomPrimary(idGenerator.nextId());
            projectTeacher.setProjectId(projectId);
            projectTeacher.setTeacherId(teacherId);
            projectTeacherMapper.insert(projectTeacher);
        }
    }


    @Override
    @Cacheable(key = "#keywords + '' + #tag + '' + #page + '' + #size" , unless = "#result == null")
    public IPage<ProjectSummaryResponse> getProjectsByCondition(String keywords, String tag, int page, int size) {
        // 定义查询条件
        LambdaQueryWrapper<YanchuangProjectMetadata> queryWrapper = new LambdaQueryWrapper<>();

        // 1. 关键词模糊匹配
        if (!keywords.isEmpty()) {
            // 对多个字段进行模糊匹配
            queryWrapper.like(YanchuangProjectMetadata::getExhibitionCode, keywords)
                .or().like(YanchuangProjectMetadata::getProjectName, keywords)
                .or().like(YanchuangProjectMetadata::getIntroduction, keywords)
                .or().like(YanchuangProjectMetadata::getInnovation, keywords)
                .or().like(YanchuangProjectMetadata::getValue, keywords)
                .or().like(YanchuangProjectMetadata::getTeam, keywords);
        }

        // 2. 根据标签名称筛选项目
        if (!tag.isEmpty()) {
            // 根据标签名称从 yanchuang_tag 表中查询 tagId
            YanchuangTag tagEntity = tagMapper.selectOne(
                new LambdaQueryWrapper<YanchuangTag>().eq(YanchuangTag::getTagName, tag).last("LIMIT 1"));

            if (tagEntity != null) {
                Long tagId = tagEntity.getCustomPrimary();

                // 根据 tagId 从 yanchuang_project_tag 表中查询所有关联的 projectId
                List<YanchuangProjectTag> projectTags = projectTagMapper.selectList(
                    new LambdaQueryWrapper<YanchuangProjectTag>().eq(YanchuangProjectTag::getTagId, tagId));

                if (projectTags != null && !projectTags.isEmpty()) {
                    // 提取所有的 projectId 作为过滤条件
                    List<Long> projectIds = projectTags.stream()
                        .map(YanchuangProjectTag::getProjectId)
                        .collect(Collectors.toList());

                    // 将 projectId 列表添加到查询条件中
                    queryWrapper.in(YanchuangProjectMetadata::getCustomPrimary, projectIds);
                } else {
                    // 如果没有项目关联该标签，则返回空分页结果
                    return new Page<>(page, size, 0);
                }
            } else {
                // 如果找不到对应的标签，则返回空分页结果
                return new Page<>(page, size, 0);
            }
        }

        // 查询项目基础信息分页列表
        IPage<YanchuangProjectMetadata> projectPage = projectMetadataMapper.selectPage(new Page<>(page, size), queryWrapper);

        // 创建返回对象的分页实例
        IPage<ProjectSummaryResponse> resultPage = new Page<>(projectPage.getCurrent(), projectPage.getSize(), projectPage.getTotal());

        // 将查询到的项目基础信息转换为自定义的 ProjectSummaryResponse 对象
        List<ProjectSummaryResponse> projectSummaryList = projectPage.getRecords().stream().map(project -> {
            ProjectSummaryResponse summary = new ProjectSummaryResponse();
            summary.setId(project.getCustomPrimary());
            summary.setExhibitionCode(project.getExhibitionCode());
            summary.setProjectName(project.getProjectName());
            // 使用 ossService 获取项目图片的 URL
            if (project.getProjectImage() != null) {
                String fileWithoutExtension = project.getProjectImage().substring(0, project.getProjectImage().lastIndexOf('.'));
                String projectImageUrl = ossService.getStudyTreeResourceUrl("dataset-square-migrate", "yanchuang/" + fileWithoutExtension);
                summary.setProjectImage(projectImageUrl);
            }

            summary.setIntroduction(project.getIntroduction());

            // 查询项目的标签
            List<YanchuangProjectTag> projectTags = projectTagMapper.selectList(
                new LambdaQueryWrapper<YanchuangProjectTag>().eq(YanchuangProjectTag::getProjectId, project.getCustomPrimary()));
            if (projectTags != null && !projectTags.isEmpty()) {
                List<Long> tagIds = projectTags.stream().map(YanchuangProjectTag::getTagId).collect(Collectors.toList());
                List<YanchuangTag> tags = tagMapper.selectBatchIds(tagIds);
                List<String> tagNames = tags.stream().map(YanchuangTag::getTagName).collect(Collectors.toList());
                summary.setTags(tagNames);
            }

            return summary;
        }).collect(Collectors.toList());

        // 设置转换后的记录列表到返回对象分页实例中
        resultPage.setRecords(projectSummaryList);
        return resultPage;
    }


    @Override
    @Cacheable(key = "#id" , unless = "#result == null")
    public ProjectDetailResponse getProjectDetail(Long id) {
        // 根据项目ID从数据库中查询项目基础信息
        YanchuangProjectMetadata project = projectMetadataMapper.selectById(id);
        if (project == null) {
            return null; // 项目不存在时返回 null
        }

        // 创建响应对象并填充数据
        ProjectDetailResponse vo = new ProjectDetailResponse();
        vo.setId(project.getCustomPrimary());
        vo.setExhibitionCode(project.getExhibitionCode());
        vo.setProjectName(project.getProjectName());

        // 使用 ossService 获取项目图片的 URL
        if (project.getProjectImage() != null) {
            String fileWithoutExtension = project.getProjectImage().substring(0, project.getProjectImage().lastIndexOf('.'));
            String projectImageUrl = ossService.getStudyTreeResourceUrl("dataset-square-migrate", "yanchuang/" + fileWithoutExtension);
            vo.setProjectImage(projectImageUrl);
        }

        // 构建 ContentDetail 对象并处理 introductionImage 字段
        ContentDetail introductionDetail = new ContentDetail();
        introductionDetail.setWords(project.getIntroduction()); // 将 introduction 文字赋值给 words
        if (JSON.isValidArray(project.getIntroductionImage())) {
            List<String> imageFiles = JSON.parseArray(project.getIntroductionImage(), String.class);
            List<String> imageUrls = imageFiles.stream()
                .map(file -> ossService.getStudyTreeResourceUrl("dataset-square-migrate", "yanchuang/" + file.substring(0, file.lastIndexOf('.'))))
                .collect(Collectors.toList());
            introductionDetail.setImages(imageUrls);
        }
        vo.setIntroduction(introductionDetail);

        // 构建 ContentDetail 对象并处理 innovationImage 字段
        ContentDetail innovationDetail = new ContentDetail();
        innovationDetail.setWords(project.getInnovation());
        if (JSON.isValidArray(project.getInnovationImage())) {
            List<String> imageFiles = JSON.parseArray(project.getInnovationImage(), String.class);
            List<String> imageUrls = imageFiles.stream()
                .map(file -> ossService.getStudyTreeResourceUrl("dataset-square-migrate", "yanchuang/" + file.substring(0, file.lastIndexOf('.'))))
                .collect(Collectors.toList());
            innovationDetail.setImages(imageUrls);
        }
        vo.setInnovation(innovationDetail);

        // 构建 ContentDetail 对象并处理 valueImage 字段
        ContentDetail valueDetail = new ContentDetail();
        valueDetail.setWords(project.getValue());
        if (JSON.isValidArray(project.getValueImage())) {
            List<String> imageFiles = JSON.parseArray(project.getValueImage(), String.class);
            List<String> imageUrls = imageFiles.stream()
                .map(file -> ossService.getStudyTreeResourceUrl("dataset-square-migrate", "yanchuang/" + file.substring(0, file.lastIndexOf('.'))))
                .collect(Collectors.toList());
            valueDetail.setImages(imageUrls);
        }
        vo.setValue(valueDetail);

        // 构建 ContentDetail 对象并处理 teamImage 字段
        ContentDetail teamDetail = new ContentDetail();
        teamDetail.setWords(project.getTeam());
        if (JSON.isValidArray(project.getTeamImage())) {
            List<String> imageFiles = JSON.parseArray(project.getTeamImage(), String.class);
            List<String> imageUrls = imageFiles.stream()
                .map(file -> ossService.getStudyTreeResourceUrl("dataset-square-migrate", "yanchuang/" + file.substring(0, file.lastIndexOf('.'))))
                .collect(Collectors.toList());
            teamDetail.setImages(imageUrls);
        }
        vo.setTeam(teamDetail);

        // 查询标签列表
        List<YanchuangProjectTag> projectTags = projectTagMapper.selectList(
            new LambdaQueryWrapper<YanchuangProjectTag>().eq(YanchuangProjectTag::getProjectId, id));
        if (projectTags != null && !projectTags.isEmpty()) {
            List<Long> tagIds = projectTags.stream().map(YanchuangProjectTag::getTagId).collect(Collectors.toList());
            List<YanchuangTag> tags = tagMapper.selectBatchIds(tagIds);
            List<String> tagNames = tags.stream().map(YanchuangTag::getTagName).collect(Collectors.toList());
            vo.setTags(tagNames);
        }

        // 查询成员列表
        List<YanchuangProjectMember> projectMembers = projectMemberMapper.selectList(
            new LambdaQueryWrapper<YanchuangProjectMember>().eq(YanchuangProjectMember::getProjectId, id));
        if (projectMembers != null && !projectMembers.isEmpty()) {
            List<Long> memberIds = projectMembers.stream().map(YanchuangProjectMember::getMemberId).collect(Collectors.toList());
            List<YanchuangMember> members = memberMapper.selectBatchIds(memberIds);
            List<MemberDTO> memberDTOList = members.stream().map(member -> {
                MemberDTO memberDTO = new MemberDTO();
                memberDTO.setMemberName(member.getName());
                memberDTO.setGrade(member.getGrade());
                memberDTO.setSchool(member.getSchool());
                return memberDTO;
            }).collect(Collectors.toList());
            vo.setMembers(memberDTOList);
        }

        // 查询教师列表
        List<YanchuangProjectTeacher> projectTeachers = projectTeacherMapper.selectList(
            new LambdaQueryWrapper<YanchuangProjectTeacher>().eq(YanchuangProjectTeacher::getProjectId, id));
        if (projectTeachers != null && !projectTeachers.isEmpty()) {
            List<Long> teacherIds = projectTeachers.stream().map(YanchuangProjectTeacher::getTeacherId).collect(Collectors.toList());
            List<YanchuangTeacher> teachers = teacherMapper.selectBatchIds(teacherIds);
            List<TeacherDTO> teacherDTOList = teachers.stream().map(teacher -> {
                TeacherDTO teacherDTO = new TeacherDTO();
                teacherDTO.setTeacherName(teacher.getName());
                teacherDTO.setTeacherSchool(teacher.getSchool());
                return teacherDTO;
            }).collect(Collectors.toList());
            vo.setTeachers(teacherDTOList);
        }

        return vo;
    }





    @Override
    public void submitComment(Long projectId, String contactInformation, String comment) {
        Long commentId = idGenerator.nextId();
        YanchuangComment commentEntity = new YanchuangComment();
        commentEntity.setCustomPrimary(commentId);
        commentEntity.setProjectId(projectId);
        commentEntity.setContactInformation(contactInformation);
        commentEntity.setComment(comment);
        commentMapper.insert(commentEntity);
    }



    @Override
    public List<YanchuangExhibitionTime> updateExhibitionStatus() {
        // 查询所有展览项目
        List<YanchuangExhibitionTime> exhibitions = exhibitionTimeMapper.selectList(new LambdaQueryWrapper<>());

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 更新每个展览的状态
        for (YanchuangExhibitionTime exhibition : exhibitions) {
            String newStatus;

            if (now.isBefore(exhibition.getStartTime())) {
                newStatus = "未开始";
            } else if (now.isAfter(exhibition.getEndTime())) {
                newStatus = "已结束";
            } else {
                newStatus = "进行中";
            }

            // 判断是否需要更新
            if (!newStatus.equals(exhibition.getCurrentStatus())) {
                exhibition.setCurrentStatus(newStatus);
                // 更新数据库中的状态
                exhibitionTimeMapper.updateCurrentStatus(exhibition.getId(), newStatus);
            }
        }

        // 返回更新后的展览列表
        return exhibitions;
    }
}
